<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Classname;
use App\Models\Points;
use App\Models\Stu;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;

class ClassController extends Controller
{
    //
    public function Index(Request $request)
    {
        return view('admin.class.list');
//        $class = Classname::paginate(10);
//        return view('admin.class.list');
    }

    public function data()
    {
        $data = Classname::orderBy('add_time', 'DESC')->get();
        return response()->json($data)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    }

    public function Create()
    {
        return view('admin.class.create');
    }

    public function Update($id)
    {
        $class = Classname::find($id);
        return view('admin.class.edit', compact('class'));
    }

    public function Edit(Request $request, $id)
    {
        $class = Classname::find($id);
        $name = $request->input('name');
        $bz = $request->input('bz');
        $update_time = Carbon::now()->toDateTimeString();
        $class->name = $name;
        $class->bz = $bz;
        $class->update_time = $update_time;
        $res = $class->save();
        if ($res) {
            return \redirect()->back()->with('success', '恭喜，修改成功！');
        } else {
            return \redirect()->back()->with('errors', '修改失败！');
        }
//        json_encode($data);
        return $data;
    }

    public function Add(Request $request)
    {
        //1.接受前台提交的表单数据 email pass repass
        $input = $request->all();
//        return $input;
        //2.进行表单验证
        //3.添加到数据库

        $time = Carbon::now()->toDateTimeString();
        $res = Classname::create(['name' => $input['name'], 'bz' => $input['bz'], 'add_time' => $time, 'add_user' => session()->get('user')->username]);
//        return $res;
        //4.根据添加是否成功，给客户端返回一个json格式的反馈
        if ($res) {
            return \redirect()->back()->with('success', '恭喜，添加成功！');
        } else {
            return \redirect()->back()->with('errors', '添加失败！');
        }
    }

    public function class_user($user)
    {
        $user = Stu::orderBy('stu_xh', 'ASC')->where('class_id', $user)->get();
        $data = "<select name='username' id='user' class='width-100'>";
        $data .= "<option value='0'>请选择成员</option>";


        foreach ($user as $v) {
            $data .= "<option value = '" . $v->id . "'>" . $v->user_name . "</option >";
        }
        $data .= "</select >";
        return $data;
    }

    public function Del($id)
    {
        $class = Classname::find($id);
        $res = $class->delete();
        if ($res) {
            return \redirect()->back()->with('success', '恭喜，删除成功！');
        } else {
            return \redirect()->back()->with('errors', '删除失败！');
        }
//        json_encode($data);
        return $data;
    }
}
